package com.coder.rental.security;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailHandler loginFailHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CustomerAnonymousEntryPoint customerAnonymousEntryPoint;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private VerifyTokenFilter verifyTokenFilter;

    /**
     * 配置Security过滤链
     *
     * 此方法主要用于配置HTTP请求的安全约束，包括登录认证、会话管理、请求授权、异常处理、CORS和CSRF配置
     *
     * @param http HttpSecurity实例，用于配置Web安全
     * @return SecurityFilterChain对象，代表配置好的安全过滤链
     * @throws Exception 配置过程中可能抛出的异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)
        throws Exception{
        // 登录前过滤配置
        http.addFilterBefore(verifyTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //登录过程处理
        http.formLogin()
                .loginProcessingUrl("/rental/user/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .requestMatchers("/rental/user/login")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(customerAnonymousEntryPoint)
                .accessDeniedHandler(customerAccessDeniedHandler)
                .and()
                .cors()
                .and()
                .csrf().disable()
                .userDetailsService(customerUserDetailsService);

        // 构建并返回配置好的Security过滤链
        return http.build();
    }

}
